# import cv2
# import os
# import datetime

# def create_output_directory(base_dir="dataset"):
#     """创建带时间戳的输出目"""
#     timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
#     output_dir = os.path.join(base_dir, f"capture_{timestamp}")
#     if not os.path.exists(output_dir):
#         os.makedirs(output_dir)
#     return output_dir

# def capture_dataset():
#     # 初始化摄像头
#     cap = cv2.VideoCapture(0)  # 0表示默认摄像头，可根据实际设备修
#     if not cap.isOpened():
#         print("Error: Could not open camera.")
#         return

#     # 设置摄像头分辨率（可根据需要调整）
#     cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
#     cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
 
#     # 验证实际分辨
#     actual_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
#     actual_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
#     print(f"Camera resolution: {actual_width}x{actual_height}")

#     # 创建输出目录
#     output_dir = create_output_directory()
#     print(f"Saving images to: {output_dir}")

#     # 拍摄参数
#     frame_count = 0
#     max_images = 1000  # 最大拍摄数

#     try:
#         while frame_count < max_images:
#             # 读取
#             ret, frame = cap.read()
#             if not ret:
#                 print("Error: Failed to capture frame.")
#                 break

#             # 显示拍摄计数和提
#             # status_text = f"Captured: {frame_count} / {max_images} (Press 's' to capture, 'q' to quit)"
#           #  cv2.putText(frame, status_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

#             # 显示预览
#             cv2.imshow("Camera Preview", frame)

#             # 键盘控制
#             key = cv2.waitKey(1) & 0xFF
#             if key == ord('q'):  # 按q退
#             # print("Capture stopped by user.")
#                 break
#             elif key == ord(' '):  # 按空格手动拍�?
#                 timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")
#                 filename = os.path.join(output_dir, f"number{frame_count}.jpg")
#                 try:
#                     cv2.imwrite(filename, frame)
#                     frame_count += 1
#                     print(f"Manually captured image {frame_count}: {filename}")
#                 except Exception as e:
#                     print(f"Error saving image: {str(e)}")

#         print(f"Capture completed. Total images: {frame_count}")

#     except Exception as e:
#         print(f"An error occurred: {str(e)}")

#     finally:
#         # 清理
#         cap.release()
#         cv2.destroyAllWindows()

# if __name__ == "__main__":
#     print("Starting dataset capture...")
#   #  print("Press 'q' to quit, 's' to capture manually")
#     capture_dataset()


import cv2
import os
import datetime
import time

def create_output_directory(base_dir="dataset"):
    """创建带时间戳的输出目�?"""
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    output_dir = os.path.join(base_dir, f"capture_{timestamp}")
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    return output_dir

def capture_dataset():
    # 初始化摄像头
    cap = cv2.VideoCapture(0)  # 0表示默认摄像头，可根据实际设备修�?
    if not cap.isOpened():
        print("Error: Could not open camera.")
        return

    # 设置摄像头分辨率（可根据需要调整）
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
 
    # 验证实际分辨�?
    actual_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    actual_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
    print(f"Camera resolution: {actual_width}x{actual_height}")

    # 创建输出目录
    output_dir = create_output_directory()
    print(f"Saving images to: {output_dir}")

    # 拍摄参数
    frame_count = 0
    max_images = 700  # 最大拍摄数�?
    capture_interval = 1  # 拍摄间隔（秒�?
    last_capture_time = time.time()

    try:
        while frame_count < max_images:
            # 读取�?
            ret, frame = cap.read()
            if not ret:
                print("Error: Failed to capture frame.")
                break

            # 显示拍摄计数和提�?
            status_text = f"Auto-capturing: {frame_count} / {max_images} (1 image/sec)"
            next_capture_text = f"Next capture in: {capture_interval - (time.time() - last_capture_time):.1f}s"
            instruction_text = "Press 'q' to quit, ' ' to manually capture"
            
            # cv2.putText(frame, status_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
            # cv2.putText(frame, next_capture_text, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
            # cv2.putText(frame, instruction_text, (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

            # 显示预览
            cv2.imshow("Camera Preview", frame)

            # 检查是否到了拍摄时�?
            current_time = time.time()
            if current_time - last_capture_time >= capture_interval:
                timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
                filename = os.path.join(output_dir, f"image_{timestamp}.jpg")
                try:
                    cv2.imwrite(filename, frame)
                    frame_count += 1
                    last_capture_time = current_time
                    print(f"Auto-captured image {frame_count}: {filename}")
                except Exception as e:
                    print(f"Error saving image: {str(e)}")

            # 键盘控制
            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):  # 按q退�?
                print("Capture stopped by user.")
                break
            elif key == ord(' '):  # 按空格手动拍�?
                timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")
                filename = os.path.join(output_dir, f"manual_{frame_count}.jpg")
                try:
                    cv2.imwrite(filename, frame)
                    frame_count += 1
                    print(f"Manually captured image {frame_count}: {filename}")
                except Exception as e:
                    print(f"Error saving image: {str(e)}")

        print(f"Capture completed. Total images: {frame_count}")

    except Exception as e:
        print(f"An error occurred: {str(e)}")

    finally:
        # 清理资源
        cap.release()
        cv2.destroyAllWindows()

if __name__ == "__main__":
    print("Starting dataset capture...")
    print("Auto-capturing 1 image per second")
    print("Press 'q' to quit, ' ' to manually capture")
    capture_dataset()